package lp2.projetoagenda;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;
import java.util.Scanner;

public class Gerenciador {
	Usuario usuario;

	public Gerenciador(){
		 try {  
			         File file = new File("Dados.txt");  
			       
			          
			         boolean success = file.createNewFile();  
			        if (success) {  
			        	usuario = new Usuario("","","");
			        	cadastrarUsuario();
			         } else {  
			             usuario = leArquivoObjeto();
			        }  
			     } catch (IOException e) {  
			     } 
			     
	}
	
	public  void escreveArquivoObjeto(Usuario p) throws IOException{
		ObjectOutputStream out = null;
		String nome = "Dados.txt";
		try{
			out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(nome)));
			out.writeObject(p);			
		}catch(IOException e){
			System.err.println(e.getMessage());
		}finally{
			out.close();
		}
	}
	
	public  Usuario leArquivoObjeto() throws IOException{
		ObjectInputStream in = null;
		Usuario p = null;
		String nome = "Dados.txt";
		try{
			in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(nome)));
			p = (Usuario) in.readObject();
		}catch(ClassNotFoundException e){
			System.err.println(e.getMessage());
		}catch(IOException e){
			System.err.println(e.getMessage());
		}finally{
			in.close();
		}
		return p;
	}
	public void cadastrarUsuario() throws IOException{
		Scanner teclado = new Scanner(System.in);
		System.out.println("Nome?");
		usuario.setNome(teclado.nextLine());
		System.out.println("Email?");
		usuario.setEmail(teclado.nextLine());
		System.out.println("Descricao?");
		usuario.setDescricao(teclado.nextLine());
		escreveArquivoObjeto(usuario);
		
	}
	public Usuario getUsuario(){
		return usuario;
	}
	public void mostraUsuario(){
		System.out.println(usuario.toString());
	}

}
